class LoginController < ApplicationController
  layout 'no_login'
  skip_before_action :require_login, only: [:to_login, :login]

  def to_login
    @user = User.new
  end

  def login
    @user = User.new(params[:user])
    if @user.username.empty?
      @user.errors.add(:username, "can't be blank")
    end
    if @user.password.empty?
      @user.errors.add(:password, "can't be blank")
    end

    if @user.errors.empty?
      user_persistent = User.find_by_username(params[:user][:username])
      if user_persistent && user_persistent.password == Digest::MD5.hexdigest(@user.password)
        @user = user_persistent
      else
        @user.errors.add(:password, 'Username or Password invalid')
      end
    end

    if @user.errors.empty?
      session[:user_id] = @user.id
      redirect_to root_path
    else
      render 'to_login'
    end
  end


  def logout
    session[:user_id] = nil
    redirect_to login_path
  end

end